import React from 'react'
import { useSelector, useDispatch } from 'react-redux'
import type { StateType } from '../store'
import { addTodo, removeTodo, TodoItemType, toggleCompleted } from '../store/totoList'
import { nanoid } from '@reduxjs/toolkit'
const TodoList: React.FC = () => {
  const todoList = useSelector<StateType>(state => state.todoLis) as TodoItemType[]
  const dispatch = useDispatch()

  function add() {
    const id = nanoid(5)
    const newAdd = {
      id,
      title: `todo${id}`,
      completed: false,
    }

    dispatch(addTodo(newAdd))
  }

  function del(id: string) {
    dispatch(removeTodo({ id }))
  }

  function toggle(id: string) {
    dispatch(toggleCompleted({ id }))
  }

  return (
    <div>
      <h1>todoList demo</h1>
      <div>
        <button onClick={add}>添加 todo</button>
      </div>
      <ul>
        {todoList.map(todo => {
          return (
            <li key={todo.id} style={{ textDecoration: todo.completed ? 'line-through' : '' }}>
              <span
                onClick={() => {
                  toggle(todo.id)
                }}
              >
                {todo.title}
              </span>
              &nbsp;
              <button
                onClick={() => {
                  del(todo.id)
                }}
              >
                删除
              </button>
            </li>
          )
        })}
      </ul>
    </div>
  )
}

export default TodoList
